using System.Collections;
using UnityEngine;

public class AngieBird : MonoBehaviour
{
    [SerializeField] private GameObject deathParticle;
    private Rigidbody2D rb;
    private CircleCollider2D circleCollider2D;
    private bool hasBeenLaunched = false;
    private bool shouldFaceVelDirection = false;
    private readonly float checkGameStateTime = 4f;
    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        circleCollider2D = GetComponent<CircleCollider2D>();
    }

    private void Start()
    {
        rb.isKinematic = true;
        circleCollider2D.enabled = false;
    }

    private void FixedUpdate()
    {
        // 在空中的时候让小鸟的面朝向与移动方向相同 velocity表示运动向量
        if (hasBeenLaunched && shouldFaceVelDirection)
        {
            transform.right = rb.velocity;
        }
    }

    public void LaunchBird(Vector2 direction, float force)
    {
        rb.isKinematic = false;
        circleCollider2D.enabled = true;
        // apply the force
        rb.AddForce(direction * force, ForceMode2D.Impulse);
        // 允许发射小鸟允许小鸟X轴朝向运动向量
        hasBeenLaunched = true;
        shouldFaceVelDirection = true;
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        // 碰撞后不允许小鸟X轴朝向运动向量
        shouldFaceVelDirection = false;
        // 移除小鸟同时检测游戏状态
        StartCoroutine(DestroyBirdAndCheckGameState());
    }

    private IEnumerator DestroyBirdAndCheckGameState()
    {
        yield return new WaitForSeconds(checkGameStateTime);
        Instantiate(deathParticle, transform.position, Quaternion.identity);
        Destroy(gameObject);
        GameManager.instance.CheckGameState();
    }
}
